import { Component,OnInit} from '@angular/core';
import {CodeService} from '../my-service/code.service';
import {UtilService} from '../my-service/util.service';
import {RollService} from '../my-service/roll.service';
import { Router} from '@angular/router';
import {Store,Select} from '@ngxs/store';
import {SetNav,SetBackgroundVaried} from '../app.state';
@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
})
export class IndexComponent  implements OnInit {
  searchText = null;
  codeLength: number = 8;
  localRecordData = [];//本地搜索记录
  appNameList = [];//保存应用名称
  currentAppName: string;//当前应用搜索名称
  key: string;//本次存储名称
  recentlyRecord: any;//最近记录
  flage = false;//当前进入码是否存在于本地存储中
  localIndex = null;//当前应用存在于本地存储中的索引
  currentSeach = {
    name: '',
    code: '',
    enterTime: 0,
    clientAddress: '',
    source: '',//获取当前来自来个班级
    classGuid: '',
    projcetName: '',//项目名称
  };//当前搜索对象
  constructor(
    private codeService: CodeService,
    private utilService: UtilService,
    private rollService: RollService,
    private route:Router,
    private store:Store
  ) {
    this.store.dispatch(new SetNav('index'));
    this.key = utilService.localStoragyKey;
    //从缓存中读取
    this.localRecordData = JSON.parse(window.localStorage.getItem(this.key));
    if (this.localRecordData) {
      //有记录,读取当前30天的记录
      let time = this.utilService.getTimeTampLatly(new Date());//获取一个月前的记录
      this.localRecordData.forEach((item, index) => {
        if (item.enterTime < time) {
          this.localRecordData.splice(index, 1);
        }
      });
      //获取最近进入的记录
      this.recentlyRecord = this.localRecordData[this.localRecordData.length - 1];
    } else {
      //没有记录
      this.localRecordData = [];
    }
  }

  ngOnInit() {
    this.codeService.getAppNameList().then(res => {
      this.store.dispatch(new SetBackgroundVaried(true));
      if (res.status == 1) {
        this.appNameList = res.data;
      }
    });
  }

  //搜索
  search() {
    this.searchText = this.utilService.trim(this.searchText);
    if (this.searchText.length >= 2) {
      // 去获取应用名称
      let subCode = this.searchText.substring(0, 2);
      let appName = this.appNameList.find((list) => {
        return list.ProjectCode == subCode;
      });
      if (appName) {
        this.currentSeach.name = appName.ProjectName;
        this.currentAppName = appName.ProjectName;
      }
    } else {
      this.currentAppName = null;
    }
    if (this.searchText.length == this.codeLength) {
      // 搜索地址
      this.codeService.searchAppUrl(this.searchText).then(res => {
        if (res.status == 1) {
          let enterTime = this.utilService.getTimeTamp(new Date());
          this.currentSeach.source = '匿名模式';
          this.currentSeach.projcetName = this.currentAppName;
          if (res.data.FK_ClassGuid) {
            //当前推送为非匿名模式
            let classGuid = '"' + res.data.FK_ClassGuid + '"';
            this.rollService.getClassList(classGuid).then(re => {
              if (re.status == 1 && re.data[0]) {
                this.currentSeach.source = re.data[0].ClassName ? re.data[0].ClassName : '匿名模式';
                this.currentSeach.classGuid = res.data.FK_ClassGuid;
              }
            })
          }
          this.currentSeach.code = this.searchText;
          this.currentSeach.enterTime = enterTime;
          this.currentSeach.clientAddress = res.data.ClientAddress;
          if (this.localRecordData[0]) {
            this.localRecordData.forEach((data, index) => {
              if (data.code == this.searchText) {
                this.flage = true;
                this.localIndex = index;
              }
            })
          }
        } else if (res.status == 3) {
          window.alert('您输入的邀请码已过期或者不存在');
        } else {
          window.alert('服务器内部错误，稍后再试');
        }
      })
    }
  }

  //进入应用
  enterApp() {
    if(this.currentSeach.name){
      if (this.searchText.length !== this.codeLength) {
        window.alert('请出入8位邀请码');
      } else {
        if (this.flage) {
          //本地存储中有相同的
          this.localRecordData.splice(this.localIndex, 1);
        }
        this.localRecordData.push(this.currentSeach);
        //存入本地
        let localRecordDataString = JSON.stringify(this.localRecordData);
        window.localStorage.setItem(this.key, localRecordDataString);
        if (this.searchText.substring(0, 2) == 'sr') {
          // 当前进入码为花名册,本应用路由跳转
          this.store.dispatch(new SetBackgroundVaried(false));
          this.route.navigate(['/home/enter',this.currentSeach.classGuid])
        } else {
          this.flage = false;
          this.localIndex = null;
          window.location.href=this.currentSeach.clientAddress;
        }
      }
    }else {
      // window.alert('请出入8位邀请码');
    }
  }

  //从最近记录进入
  goApp(data) {
    if (data.code.substring(0, 2) == 'sr') {
      //从路由进入
      this.store.dispatch(new SetBackgroundVaried(false));
      this.route.navigate(['/home/enter',data.classGuid]);
    }else {
      window.location.href=data.clientAddress
    }
  }
}
